from django.http import JsonResponse
#
import random
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.client import CommonRequest


class HttpCode(object):
    ok = 200
    paramserror = 400
    methoderror = 405
    servererror = 500

def result(code=HttpCode.ok,message='',data=None,kwargs=None):
    json_dict = {'code':code,'message':message,'result':data}

    if kwargs and isinstance(kwargs,dict) and kwargs.keys():
        json_dict.update(kwargs)
    return JsonResponse(json_dict,json_dumps_params={'ensure_ascii':False})

def ok(message,data=None):
    return result(code=HttpCode.ok,message=message,data=data)

def params_error(message='',data=None):
    return result(code=HttpCode.paramserror,message=message,data=data)

def method_error(message='',data=None):
    return result(code=HttpCode.servererror,message=message,data=data)

def server_error(message='',data=None):
    return result(code=HttpCode.servererror,message=message,data=data)




def send_sms(phone,code):
    client = AcsClient('LTAIwcVRm7iZ7pIg','KQ4AgwtaJQPTjLJEQ1X6ltVNHNLcli','cn-hangzhou')
    code = '{"code":%s}'%(code)
    request = CommonRequest()
    request.set_accept_format('json')
    request.set_domain('dysmsapi.aliyuncs.com')
    request.set_method('POST')
    request.set_protpcol_type('https')
    request.set_version('2019-08-13')
    request.set_action_name('sendSms')

    request.add_query_param('RegionId','cn-hangzhou')
    request.add_query_param('PhoneNumbers',phone)
    request.add_query_param('SignName','')
    request.add_query_param('TemplateCode','')
    request.add_query_param('TemplateParam',code)

    response = client.do_action(request)

    print(str(response,encoding='utf-8'))

    return str(response,encoding='ut-8')

def get_code(n=6,alpha=True):
    s= ''
    for i in range(n):
        num = random.randint(0,9)
        if alpha:
            upper_alpha = chr(random.randint(65,90))
            lower_alpha = chr(random.randint(97,122))
            num = random.choice([num,upper_alpha,lower_alpha])
        s = s+str(num)
    return s
if __name__ =='__main__':
    send_sms('15703470625',get_code(6,False))
    print(get_code(6, False))
    print(get_code(6, True))
    print(get_code(4, False))
    print(get_code(4, True))
#
# # 发短信接口
# def sms_send(request):
#     phone = request.GET.get('phone')
#     code = get_code(6,False)
#     cache.set(phone,code,60)
#     print('判断缓存中是否有',cache.has_key(phone))
#     print('获取redis验证码',cache.get(phone))
#     result = send_sms(phone,code)
#     return HttpResponse(result)
# # 短信验证码校验
# def sms_check(request):
#     phone = request.GET.get('phone')
#     code = request.GET.get('code')
#     print('缓存中是否有:',cache.has_key(phone))
#     print('取值'),cache.get(phone)
#     cache_code = cache.get(phone)
#     if code == cache_code:
#         return restful.ok('ok',data=None)
#     else:
#         return restful.params_error('验证码错误',data=None)


# def